package com.hk.blog.repository.jpa.impl;

import com.hk.blog.repository.jpa.custom.CustomArticleInfoRepository;
import com.hk.blog.vo.ArticleListVo;
import com.hk.blog.vo.ArticleSearchBean;
import com.hk.commons.query.Operator;
import com.hk.commons.query.Order;
import com.hk.commons.query.QueryModel;
import com.hk.commons.query.page.QueryPage;
import com.hk.core.jdbc.JdbcDaoSupport;
import com.hk.core.jdbc.SelectArguments;
import com.hk.core.jdbc.query.SimpleCondition;

import java.util.Map;

public class ArticleInfoRepositoryImpl extends JdbcDaoSupport implements CustomArticleInfoRepository {

    @Override
    public QueryPage<ArticleListVo> findForPage(QueryModel<ArticleSearchBean> queryModel) {
        SelectArguments arguments = SelectArguments.newSelectArguments(queryModel);
        arguments.fields("t1.id,title,t1.protect,t1.browse_num,t1.last_modified_date,t2.category_name")
                .setFrom("t_article_info t1 LEFT JOIN t_category_info t2 ON t1.category_id = t2.id")
                .setCountField("t1.id");
        if (queryModel.getOrders().isEmpty()) {
            arguments.addOrder(Order.asc("t1.last_modified_date"));
        } else {
            Map<String, String> orderFieldMap = Map.of("lastModifiedDate", "t1.last_modified_date",
                    "browseNum", "t1.browse_num");
            queryModel.getOrders()
                    .stream().filter(item -> orderFieldMap.containsKey(item.getField()))
                    .forEach(item -> item.setField(orderFieldMap.get(item.getField())));
            arguments.setOrders(queryModel.getOrders());
        }
        ArticleSearchBean param = queryModel.getParam();
        if (null != param) {
            arguments.getConditions().addConditions(
                    new SimpleCondition("t1.user_id", param.getUserId()),
                    new SimpleCondition("t1.category_id", param.getCategoryId()),
                    new SimpleCondition("t1.protect", param.getProtect()),
                    new SimpleCondition("t1.title", Operator.LIKEANYWHERE, param.getTitle()));
        }
        return jdbcSession.queryForPage(arguments, ArticleListVo.class);
    }
}
